package com.gordon.tips.util.email;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;



public class HtmlMailSender {

	// public BlockingQueue<EmailBean> emailQueue = new
	// ArrayBlockingQueue<EmailBean>(100);

	private ExecutorService es = Executors.newFixedThreadPool(10);

	private Logger log = Logger.getLogger(HtmlMailSender.class);

	private JavaMailSender mailSender;

	private String from;

	public void setFrom(String from) {
		this.from = from;
	}

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	
	public void addEmail(String toEmailAddr, String subject, String content)
			throws MessagingException {
		if (StringUtils.isNotBlank(toEmailAddr)) {
			EmailBean e = new EmailBean(toEmailAddr, subject, content);
			// if (emailQueue.offer(e)) {
			es.submit(new SendEmailThread(e));
			// }
			// sendEmail(e);
		}
	}


	private void sendEmail(EmailBean email) throws MessagingException {
		if (email != null) {
			try {
				MimeMessage msg = mailSender.createMimeMessage();
				MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
				helper.setTo(email.getToEmailAddr());
				helper.setFrom(from);
				helper.setSubject(email.getSubject());
				helper.setText(email.getContent(), true);
				mailSender.send(msg);
				log.debug("sended.");
			} catch (MessagingException e) {
				
				throw e;
			}
		}
	}

	class SendEmailThread implements Callable<Object> {
		private EmailBean e;

		public SendEmailThread(EmailBean e) {
			this.e = e;
		}

		public Object call() throws Exception {
			sendEmail(e);
			return null;
		}
	}
}